import {
  setToken,
  setUserInfos,
  setUserInfo,
  setUserWx,
  setUserRoles,
  setUserRole,
  setIsLoginProcess,
  getMpFlag,
  clearStorage,
  getIsLoginProcess,
  getToken,
  getUserInfos,
  getUserInfo,
  getUserRole,
  getUserRoles,
  getUserWx,
  getWxConfig,
  getXTenantHeader
} from '@common/auth';
import { userByWxCode } from '@api/login';
import { getUrlParams, isEmpty, serializeToUrl, getWxConfigUrl } from '@common/utils.js';
import store from '@store';
// import { userByWxCode, userLogin, userRegister } from '@api/login';
// import { updateUserInfo } from '@api/common/user';
import { qryChildrenList } from '@api/home';

/**
 * 保存用户登录信息
 * @param context
 * @param context.commit
 * @param context.dispatch
 * @param data
 */
const saveUserInfo = ({ commit, dispatch }, data) => {
  const { accessToken, userInfos = [] } = data;
  // http headers
  setToken(accessToken);
  if (isEmpty(userInfos)) return false;
  // Vuex state
  commit('setUserInfos', userInfos);
  dispatch('setUserInfo', userInfos[0]);
};

/**
 * 判断是否关注公众号
 * @param success
 * @param data
 * @returns {boolean}
 */
const isUserSubscribe = (success, data) => {
  // https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId
  try {
    const subscribe = success ? data.userInfos[0].userWx.subscribe : data.userWx.subscribe;
    const mpFlag = getMpFlag();
    if (subscribe === false && mpFlag) {
      console.log('[用户未关注]');
      // https://blog.csdn.net/J_H_S/article/details/78171105
      const redirect = {
        param: {
          action: 'home',
          __biz: mpFlag,
          scene: '110'
        },
        url: 'https://mp.weixin.qq.com/mp/profile_ext',
        hash: '#wechat_redirect'
      };
      const redirectParam = serializeToUrl(redirect.param, false);
      const redirectUrl = `${redirect.url}?${redirectParam}${redirect.hash}`;
      clearStorage(true);
      // 设置location.href并不一定会立马跳转，后面的代码仍然会被执行
      location.href = redirectUrl;
      return false;
    }
  } catch (e) {
    return false;
  }
  return true;
};

/**
 * 用户登录、注册、绑定请求成功回调函数
 * @param {Object} context
 * @param context.commit
 * @param context.dispatch
 * @param data
 */
const loginCallback = async ({ commit, dispatch }, data) => {
  setIsLoginProcess(true);
  const { accessToken, userInfos = [] } = data;
  // http headers
  setToken(accessToken);
  if (isEmpty(userInfos)) return false;
  // Vuex state
  commit('setUserInfos', userInfos);
  await dispatch('setUserInfo', userInfos[0]);

  // 有code代表第一次进入，没有code代表用户登录完成
  const { code } = getUrlParams();
  if (isEmpty(code)) return false;

  // 重定向到没有 code和state 地址，是为了配置wx.config
  await dispatch('wechat/getWxConfig', null, { root: true }).finally(() => {
    // location.replace(getWxConfigUrl());
	dispatch('wxConfiguration')
  });

  return false;
};

export default {
  namespaced: true,
  state: {
    userInfos: [], // 一个微信可能存在多个账号
    userInfo: {}, // 已选账号的用户信息
    userRoles: [], // 已选账号的角色列表
    userRole: {}, // 已选账号的当前角色
    userWx: {}, // 已选账号用户微信信息
    userTodoBadge: {} // 用户待办菜单徽标数
  },
  getters: {
    userInfos: (state) => state.userInfos,
    userInfo: (state) => state.userInfo,
    userRoles: (state) => state.userRoles,
    userRole: (state) => state.userRole,
    userWx: (state) => state.userWx,
    userTodoBadge: (state) => state.userTodoBadge
  },
  mutations: {
    setUserInfos: (state, value) => {
      value = value || [];

      setUserInfos(value);
      state.userInfos = value;
    },
    setUserInfo: (state, value) => {
      value = value || {};

      const { userName, sex, photo, openId } = value;

      const userInfo = {
        ...value,
        wxOpenId: openId,
        userName: userName || '',
        gender: sex || '0',
        faceUrl: photo || ''
      };

      setUserInfo(userInfo);
      state.userInfo = userInfo;
    },
    setUserRoles: (state, value) => {
      value = value || [];

      setUserRoles(value);
      state.userRoles = value;
    },
    setUserRole: (state, value) => {
      value = value || {};

      setUserRole(value);
      state.userRole = value;
    },
    setUserWx: (state, value) => {
      value = value || {};

      setUserWx(value);
      state.userWx = value;
    },
    setUserTodoBadge: (state, value) => {
      value = value || {};

      state.userTodoBadge = value;
    }
  },
  actions: {
    // 因为mutations没有commit，这个还会同步修改userWx、userRoles
    setUserInfo({ commit, state }, user) {
      return new Promise((resolve) => {
        const { userWx, zyPlaceRoleBOS: userRoles, ...userInfo } = user;
        const userRole = getUserRole();
        // Vuex state
        commit('setUserInfo', { ...userInfo, openId: userWx.openId });
        commit('setUserWx', userWx);
        commit('setUserRoles', userRoles);
        if (!isEmpty(userRole)) {
          const isInclude = userRoles.some((item) => item.roleCode === userRole.roleCode);
          // 给定一个默认角色
          if (!isInclude) commit('setUserRole', userRoles[0]);
        } else {
          commit('setUserRole', userRoles[0]);
        }

        resolve(true);
      });
    },
    userByWxCode(context, form) {
      return new Promise((resolve, reject) => {
        userByWxCode(form)
          .then(async ({ success, msg, data }) => {
            const isSubscribe = await isUserSubscribe(success, data);
            // 这里要加个return判断，不然后面的会被执行
            if (!isSubscribe) return false;

            if (success === true) {
              await loginCallback(context, data);
            } else if (data && data.userWx) {
              context.commit('setUserWx', data.userWx);
            }
            resolve({ success, msg, data });
          })
          .catch((error) => {
			  reject(error)
		  });
      });
    },
	wxConfiguration() {
		const userInfos = getUserInfos();
		const userInfo = getUserInfo();
		const userWx = getUserWx();
		const userRole = getUserRole();
		const userRoles = getUserRoles();
		// Vuex state
		const stateInfos = store.getters['user/userInfos'];
		const stateInfo = store.getters['user/userInfo'];
		const stateWx = store.getters['user/userWx'];
		const stateRole = store.getters['user/userRole'];
		const stateRoles = store.getters['user/userRoles'];
				
		// 设置用户信息到Vuex
		if (isEmpty(userInfos) !== isEmpty(stateInfos)) {
		  store.commit('user/setUserInfos', userInfos);
		}
		if (isEmpty(userInfo) !== isEmpty(stateInfo)) {
		  store.commit('user/setUserInfo', userInfo);
		}
		if (isEmpty(userWx) !== isEmpty(stateWx)) {
		  store.commit('user/setUserWx', userWx);
		}
		if (isEmpty(userRole) !== isEmpty(stateRole)) {
		  store.commit('user/setUserRole', userRole);
		}
		if (isEmpty(userRoles) !== isEmpty(stateRoles)) {
		  store.commit('user/setUserRoles', userRoles);
		}
		
		const isLogin = getIsLoginProcess();
		const wxConfig = getWxConfig();
		// 用户信息不为空，跳过登录到首页
		if (!isEmpty(userInfo) && !isEmpty(userWx) && isLogin) {
		  setIsLoginProcess(false);
		  // 微信配置
		  store
		    .dispatch('wechat/initWxConfig', wxConfig)
		    .catch(() => {
				console.log('user...not found')
			})
		    .finally(() => {
				uni.navigateTo({
					url: '/pages/index/home'
				})
			});
		  return false;
		}
	},
    userLogin(context, form) {
      // return new Promise((resolve, reject) => {
      //   userLogin(form)
      //     .then(async ({ success, msg, data }) => {
      //       if (success === true) {
      //         await loginCallback(context, data);
      //       }

      //       resolve({ success, msg, data });
      //     })
      //     .catch((error) => reject(error));
      // });
    },
    userRegister(context, form) {
      // return new Promise((resolve, reject) => {
      //   userRegister(form)
      //     .then(async ({ success, msg, data }) => {
      //       if (success === true) {
      //         await loginCallback(context, data);
      //       }

      //       resolve({ success, msg, data });
      //     })
      //     .catch((error) => reject(error));
      // });
    },
    updateUserInfo({ commit, state }, form) {
      // return new Promise((resolve, reject) => {
      //   updateUserInfo(form)
      //     .then(({ success, msg, data }) => {
      //       if (success === true) {
      //         const userInfo = Object.assign({}, state.userInfo, data);

      //         setUserInfo(userInfo);

      //         commit('setUserInfo', userInfo);
      //       }

      //       resolve({ success, msg, data });
      //     })
      //     .catch((error) => reject(error));
      // });
    },
    getUserChildren({ commit, state }) {
		console.log('getUserChildren')
      return new Promise((resolve, reject) => {
        qryChildrenList(state.userInfo.placeUserId)
          .then(({ success, msg, data }) => {
            if (success && data.zyUserStudentQueryRespIOS) {
              var userInfo = {
                ...state.userInfo,
                children: data.zyUserStudentQueryRespIOS,
                curChild: data.zyUserStudentQueryRespIOS[0]
              };
			  console.log(userInfo, 'setUserInfo*****')
              commit('setUserInfo', userInfo);
            }
            resolve({ success, msg, data });
          })
          .catch((error) => reject(error));
      });
    }
  }
};
